import { useState, useContext, useEffect } from "react";
import { Link, useNavigate } from "react-router-dom";
import "./login.css";
import axios from 'axios';
import { UserContext } from "../context/userContext";

const Login = () => {
  const [userData, setUserData] = useState({
    email: '',
    password: '',
  });

  const [error, setError] = useState('');
  const navigate = useNavigate();
  const { currentUser, setCurrentUser } = useContext(UserContext);

  useEffect(() => {
    if (currentUser) {
      navigate('/');
    }
  }, [currentUser, navigate]);

  const changeInputHandler = (e) => {
    e.preventDefault();
    setUserData(prevState => {
      return { ...prevState, [e.target.name]: e.target.value };
    });
  };

  const loginUser = async (e) => {
    e.preventDefault();
    setError('');
    try {
      const response = await axios.post(`${process.env.REACT_APP_BASE_URL}/users/login`, userData);
      const user = await response.data;

      setCurrentUser(user);
      navigate('/');
    } catch (err) {
      setError(err.response.data.message);
    }
  };

  return (
      <section className="login">
        <div className="text-group_1 flex-col justify-between">
          <span className="text_3">欢迎访问！</span>
          <span className="text_4">登录您的账户以继续</span>
        </div>
        <form className="form login__form" onSubmit={loginUser}>
          {error && <p className="form__error-message">{error}</p>}
          <div className="box_3 flex-row justify-between">
            <div className="image-wrapper_1 flex-col">
              <img
                  className="label_2"
                  src={"https://lanhu-oss.lanhuapp.com/FigmaDDSSlicePNGbe33209837fd2b314332d897e7b9d0a5.png"}
              />
            </div>
            <div className="text-group_2 flex-col justify-between">
              <span className="text_5">邮箱</span>
              <input className="text_8" type="text" placeholder="请输入您的邮箱" name="email" value={userData.email}
                     onChange={changeInputHandler}
                     autoFocus/>
            </div>
          </div>

          <div className="box_3 flex-row justify-between">
            <div className="image-wrapper_2 flex-col">
              <img
                  className="label_3"
                  src={"https://lanhu-oss.lanhuapp.com/FigmaDDSSlicePNGbc788a31bba3ad0c92eb3c1f40e5a172.png"}
              />
            </div>
            <div className="text-group_2 flex-col justify-between">
              <span className="text_7">密码</span>
              <input className="text_8" type="password" placeholder="请输入登录密码，支持特殊符号" name="password"
                     value={userData.password}
                     onChange={changeInputHandler}/>
            </div>
          </div>
          <div className="text-wrapper_3 flex-col">
            <button type="submit" className="text_11">登陆</button>
          </div>
          <span className="text_10"><Link to='/forget'>忘记密码？</Link></span>
          <div className="text-wrapper_2 flex-col">
            <span className="text_9"><Link to='/register'>创建账户</Link></span>
          </div>
        </form>
      </section>
  );
};

export default Login;

